package com.hmall.gateway.filter;

import cn.hutool.core.util.StrUtil;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author 31655
 */
@Component
@Slf4j
@EnableConfigurationProperties(AuthProperties.class)
@RequiredArgsConstructor
public class PrintAnyGlobalFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;

    private final JwtTool jwtTool;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.校验是否再白名单中，在放行
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String uri = request.getPath().toString();
        List<String> excludePaths = authProperties.getExcludePaths();
        for (String excludePath : excludePaths) {
            if (antPathMatcher.match(excludePath, uri)){
                return chain.filter(exchange);
            }
        }
        //2.获取token
        String token = request.getHeaders().getFirst("authorization");
        if (StrUtil.isEmpty(token)){
            response.setRawStatusCode(401);
            return response.setComplete();
        }
        //3.校验token
        Long userId;
        try {
            userId = jwtTool.parseToken(token);
        } catch (Exception e) {
            response.setRawStatusCode(401);
            return response.setComplete();
        }
        //TODO 4.获取用户信息，传递到微服务
        request.mutate().header("user-info", userId.toString());

        //5.放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
